function applyRTLToSelection () {
  const selection = window.getSelection()

  const rootNodes = getRootNodes('body')
  const anchorAncestorIndex = findRootAncestor(
    selection.anchorNode.parentElement
  )
  const focusAncestorIndex = findRootAncestor(selection.focusNode.parentElement)
  const rootNodesToBeFixed = getOrderedIntergersBetween(anchorAncestorIndex, focusAncestorIndex).map(
    x => rootNodes[x]
  )

  ultimateFix(rootNodesToBeFixed)
}

/**
 * Return all direct child elements for given root ('body' as default)
 * @param {string} selector
 * 
 * @returns {{HTMLDOMElement}[]}
 */
function getRootNodes (selector = 'body') {
  return $(selector)
    .children()
    .toArray()
}

/**
 * Find the root ancestor which is the direct child of body
 * @param {HTMLDOMElement} element
 * 
 * @returns {HTMLDOMElement}
 */
function findRootAncestor (element) {
  const rootNodes = getRootNodes('body')

  let result = -1
  while (result === -1) {
    result = rootNodes.findIndex(e => element === e)
    element = element.parentElement
  }

  return result
}

/**
 * Get integers between the range
 * @param {number} anchorIndex
 * @param {number} focusIndex
 * 
 * @returns {number[]}
 */
function getOrderedIntergersBetween (anchorIndex, focusIndex) {
  const isReverse = anchorIndex > focusIndex
  const targetLength = isReverse ? anchorIndex - focusIndex + 1 : focusIndex - anchorIndex + 1
  const arr = new Array(targetLength).fill(null)
  const result = arr.map((_, i) => {
    return isReverse ? i + focusIndex : i + anchorIndex
  })

  return result
}

/**
 * This is the placeholder for the function from SilvaQ
 * As long as we pass the root elements to be fixed,
 * this function will take care of the content in it recursively
 */
function ultimateFix (elementsToBeFixed) {
  console.log('ultimate fix got elements:', elementsToBeFixed)
  $.each(elementsToBeFixed, (_, x) => $(x).css('direction', 'rtl'))
}
